'use strict';
/**
 * This is the main interface to export the middleware(s)
 * we will take the config here and export array of middleware using koa-compose
 */
const fs = require('fs')
const merge = require('lodash.merge')
const compose = require('koa-compose')
const {
  configCheck,
  coreMiddleware,
  authMiddleware,
  contractMiddleware,
  helloMiddleware,
  consoleMiddleware,
  publicMethodMiddleware,
  errorsHandlerMiddleware,
  initMiddleware
} = require('./src')
const { getDebug } = require('./src/lib')

const debug = getDebug('main')
// main
module.exports = function(config = {}) {
  // first check the config
  const opts = configCheck(config)
  debug('[jsonql-koa] init opts', opts)
  // export
  let middlewares = [
    initMiddleware(opts),
    helloMiddleware(opts),
    contractMiddleware(opts)
  ]
  // only available when enable it
  if (config.enableWebConsole) {
    middlewares.push(consoleMiddleware(opts))
  }

  if (opts.enableAuth) {
    middlewares.push(
      publicMethodMiddleware(opts),
      authMiddleware(opts)
    )
  }
  middlewares.push(
    coreMiddleware(opts)
  )
  // finally
  return compose(middlewares)
}
